//
//  BuildNewPhoneVc.swift
//  Pods
//
//  Created by eme on 2017/4/6.
//
//

import UIKit
import UtilCore
import RxSwift
import RickonCore

class BuildNewPhoneVc: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var phone_TextField: UITextField! //电话号码输入框
    @IBOutlet weak var order_TextField: UITextField! //验证码输入框
    @IBOutlet weak var getOrder_Button: UIButton!    //获取验证码按钮
    @IBOutlet weak var complete_Button: UIButton!    //完成按钮
    
    /*----------------------------   自定义属性区域    ----------------------------*/
    /// 计时器
    var countdownTimer: Timer?
    var remainingSeconds: Int = 0 {
        willSet {
            getOrder_Button.setTitle("\(newValue)秒后重新获取", for: .normal)
            
            if newValue <= 0 {
                getOrder_Button.setTitle("重新获取验证码", for: .normal)
                isCounting = false
            }
        }
    }
    var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(BuildNewPhoneVc.updateTime(_:)), userInfo: nil, repeats: true)
                
                remainingSeconds = 60
            } else {
                countdownTimer?.invalidate()
                countdownTimer = nil
            }
            
            getOrder_Button.isEnabled = !newValue
        }
    }
    
    func updateTime(_ timer: Timer) {
        remainingSeconds -= 1
    }
    var govm:GetOrderViewModel?
    
    var bnvm:BulidNewPhoneVm?
    
    var type:String?
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        self.setupPhonetf()
        self.completeBtn()
        self.setUpGetOrderButton()
        self.getOrder_Button.rx.tap.subscribe(onNext:{ _ in
            
            self.view.endEditing(true)
            self.govm?.type = "newphone"
            self.govm?.getOrder.onNext(self.phone_TextField.text!)
            
            
            }).addDisposableTo(disposeBag)
        phone_TextField.font = UIFont(name:Theme.font.light,size:15)
        order_TextField.font = UIFont(name:Theme.font.light,size:15)
        getOrder_Button.titleLabel?.font = UIFont(name:Theme.font.light,size:13)
        complete_Button.titleLabel?.bold_fontSize(17)
    }
    func setupPhonetf(){
        phone_TextField.layer.borderWidth = 1
        phone_TextField.layer.borderColor = Theme.sansa.buildPhone.textfield_Border.cgColor
        
        order_TextField.layer.borderColor = Theme.sansa.buildPhone.textfield_Border.cgColor
        order_TextField.layer.borderWidth = 1
    }
    func completeBtn(){
        complete_Button.layer.masksToBounds = true
        complete_Button.layer.cornerRadius = 4
        complete_Button.backgroundColor = UIColor.clear
        complete_Button.changeBackgroundImage(Theme.btn.normal, highlightedColor: Theme.btn.highlighted, disabledColor: Theme.btn.disabled)
    }
    func setUpGetOrderButton(){
        
        getOrder_Button.backgroundColor = UIColor.clear
        getOrder_Button.setTitleColor(Theme.sansa.ChangePhone.CodeBtn_Title_Normal, for: .normal)
        getOrder_Button.setTitleColor(Theme.sansa.ChangePhone.CodeBtn_Title_Disabled, for: .disabled)
        getOrder_Button.setBackgroundImage(Theme.sansa.ChangePhone.CodeBtn_Bg_Disabled.getImage(), for: .disabled)
        getOrder_Button.setBackgroundImage(Theme.sansa.ChangePhone.CodeBtn_Bg_Normal.getImage(), for: .normal)
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        
        //完成按钮点击事件
        complete_Button.rx.tap.subscribe(onNext:{ _ in
            
            self.view.endEditing(true)
            self.bnvm?.code = self.order_TextField.text!
            self.bnvm?.type = "newphone"
            self.bnvm?.buildPhone.onNext(self.phone_TextField.text!)
            
        }).addDisposableTo(disposeBag)
        
        //判断是否可点击获取验证码
        
        let valid = phone_TextField.rx.text
            .map{$0! =~ validationRegExp.mobile}
        
        valid
            .bindTo(getOrder_Button.rx.isEnabled)
            .addDisposableTo(disposeBag)
        
        valid.asObservable().subscribe(onNext:{ invalid in
            
            if self.getOrder_Button.isEnabled && self.remainingSeconds == 0{
                
                self.getOrder_Button.isEnabled = true
            }else{
                
                self.getOrder_Button.isEnabled = false
            }
        }).addDisposableTo(disposeBag)
        
        
        //---------
        //绑定新手机()
        
        let complete = Observable.combineLatest(order_TextField.rx.text.map{$0!.characters.count >= 4}, phone_TextField.rx.text.map{$0! =~ validationRegExp.mobile}){ item1,item2 in
            return item1 && item2
        }
        
        complete
            .bindTo(complete_Button.rx.isEnabled)
            .addDisposableTo(disposeBag)
        
        
        //-------------
        //获取验证码
        self.govm = GetOrderViewModel()
        
        govm?.backMessage.subscribe(onNext:{ data in
            if data == true{
                
                self.isCounting = true
            }
        }).addDisposableTo(disposeBag)
        
        self.govm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        
        
        //-------------
        //验证验证码是否正确
        self.bnvm = BulidNewPhoneVm()
        
        self.bnvm?.backMessage.subscribe(onNext:{ result in
            if result == true{
                
                self.phone_TextField.text = ""
                self.order_TextField.text = ""
                
                self.view.toastCompletion("修改成功", completion: {[unowned self] _ in
                    let vc = self.navigationController?.viewControllers[2]
                    _ = self.navigationController?.popToViewController(vc!, animated: true)
                })
            }
        }).addDisposableTo(disposeBag)
        
        self.bnvm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        
    }
}
